<?php

namespace Xrfg\Wallet\TRX\Console;

use App\Models\WtrcCollect;
use Illuminate\Console\Command;
use App\Models\Coin;
use Illuminate\Support\Facades\DB;
use Xrfg\Wallet\TRX\Jobs\CollectJob;
use Xrfg\Wallet\TRX\Services\TRXWallet;

class CollectTRC20 extends Command
{
    protected $signature = 'collect:trc20 {coin_name}';

    protected $description = 'TRC20 归集';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $coin_name = strtoupper($this->argument('coin_name'));
        $coin = Coin::where('name', $coin_name)->first();
        if (!$coin) {
            return;
        }

        $balance = (new TRXWallet(config('wallet.trx.node.wallet')))->getBalance(config('wallet.trx.withdraw_address'));
        if ($balance < 10) {
            return;
        }

        WtrcCollect::where('status', 0)
            ->chunk(1000, function ($collect_list) use ($coin_name) {
                foreach ($collect_list as $collect) {
                    logger('=====================collect=========================================');
                    logger($collect);
                    if (strtoupper($collect->address) == strtoupper('TYfh7JDPfdjm32Pp2DUGCuw9To6aKsw6C2')) {
                        logger("{$collect->address}不归集");
                        continue;
                    }

                    DB::transaction(function() use ($collect, $coin_name) {
                        $collect = WtrcCollect::lockForUpdate()->find($collect->id);
                        if ($collect->status == 0) {
                            $collect->status = 1;
                            $collect->save();

                            // 转TRX手续费
                            logger('=====================collect transfer TRX============================');
                            $txid = (new TRXWallet(config('wallet.trx.node.wallet')))->doTransferTRX(config('wallet.trx.withdraw_address'),config('wallet.trx.password'),$collect->address,0.3);
                            logger("txid:{$txid}");

                            // 转USDT-TRC20（延迟10分钟执行，以确保手续费已到账）
                            CollectJob::dispatch($coin_name, $collect)->delay(now()->addMinutes(5))->onQueue('collect');
                        }
                    });
                }
            });

    }
}
